package org.phpsx.amun.newsreader;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Properties;

import javax.swing.JOptionPane;

import com.k42b3.neodym.ServiceItem;
import com.k42b3.neodym.oauth.Oauth;
import com.k42b3.neodym.oauth.OauthProvider;

/**
 * Auth
 * 
 * @author     Christoph Kappestein <k42b3.x@gmail.com>
 * @license    http://www.gnu.org/licenses/gpl.html GPLv3
 * @link       http://amun.phpsx.org
 * @category   example
 * @package    newsreader
 * @version    $Revision: 628 $
 */
public class Auth
{
	public Auth()
	{
		try
		{
			// oauth config
			ServiceItem request = Newsreader.getAvailableServices().getItem("http://oauth.net/core/1.0/endpoint/request");
			ServiceItem authorization = Newsreader.getAvailableServices().getItem("http://oauth.net/core/1.0/endpoint/authorize");
			ServiceItem access = Newsreader.getAvailableServices().getItem("http://oauth.net/core/1.0/endpoint/access");

			if(request == null)
			{
				throw new Exception("Could not find request service");
			}

			if(authorization == null)
			{
				throw new Exception("Could not find authorization service");
			}

			if(access == null)
			{
				throw new Exception("Could not find access service");
			}

			OauthProvider provider = new OauthProvider(request.getUri(), authorization.getUri(), access.getUri(), Newsreader.CONSUMER_KEY, Newsreader.CONSUMER_SECRET);
			Oauth oauth = new Oauth(Newsreader.getHttp(), provider);

			if(oauth.requestToken())
			{
				if(oauth.authorizeToken())
				{
					if(oauth.accessToken())
					{
						JOptionPane.showMessageDialog(null, "You have successful authenticated");

						saveConfig(oauth.getToken(), oauth.getTokenSecret());

						// start application
						new Newsreader();
					}
				}
			}
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());

			e.printStackTrace();
		}
	}

	private void saveConfig(String token, String tokenSecret)
	{
		try
		{
			Properties prop = new Properties();
			prop.setProperty("token", token);
			prop.setProperty("token_secret", tokenSecret);

			File config = new File(Newsreader.CONFIG_FILE);
			prop.storeToXML(new FileOutputStream(config), null);
		}
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "The following error occured: " + e.getMessage() + "\nNevertheless you can use the obtained token and token secret by adding them manually to the configuration file.\n\nToken: " + token + "\nToken secret: " + tokenSecret);
		}
	}
}
